const querystring = require('querystring')
const char_collection = '0123456789abcdefghijklmnopqrstuvwxyz'

/**
 *
 * description:String Util
 * create by mirko
 * 1061773869@qq.com
 *
 */


/**
 *
 * 将对象转化成查询字符串且查询key会根据字典排序
 *
 */
function object2SearchString(object) {
    if (!(object instanceof Object)) {
        throw new Error(`${object} must be an object`)
    }
    let keys = Object.keys(object);
    let tempKey = keys.sort();
    let temp_obj = {};
    tempKey.forEach(value => {
        if (typeof object[value] === "object") {
            temp_obj[value] = JSON.stringify(object[value])
        } else {
            temp_obj[value] = object[value]
        }
    });
    return querystring.unescape(querystring.stringify(temp_obj))
}

/**
 *
 * 将查询字符串转换成对象
 *
 */
function searchString2Object(search_string) {
    let object = querystring.parse(search_string);
    let temp_obj = {};
    let keys = Object.keys(object);
    keys.forEach(value => {
        temp_obj[value] = object[value]
    });
    if (!(temp_obj instanceof Object)) {
        throw new Error(`${search_string} can't be parse to an object`)
    }
    return temp_obj
}

/**
 *
 * 生成固定长度随机字符串
 *
 */
function getRandChar(length) {
    let result = '';
    for (let i = 0; i < length; i++) {
        result = result + char_collection[Math.floor(Math.random() * char_collection.length + 1)]
    }
    return result;
}

/**
 *
 *
 * 根据前缀随机生成订单号
 *
 *
 */
function generateTradeNo(header) {
    let randomStr = Math.random().toString().substr(2, 11);
    let timestamp = Date.now();
    let trade_no = header + timestamp + randomStr;
    return trade_no;
}


module.exports.searchString2Object = searchString2Object;
module.exports.object2SearchString = object2SearchString;
module.exports.getRandChar = getRandChar;
module.exports.generateTradeNo = generateTradeNo
